package pers.cz.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import pers.cz.netty.filter.IFilter;
import pers.cz.netty.handler.HeartBeatHandler;
import pers.cz.netty.handler.IdleStateHandler;
import pers.cz.netty.handler.MessageHandler;
import pers.cz.netty.listener.Listener;
import pers.cz.netty.protocal.Message;
import pers.cz.netty.protocal.ProtocalConst;
import pers.cz.netty.protocal.TcpMessageDecoder;
import pers.cz.netty.protocal.TcpMessageEncoder;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * @program: PostGirl-panent
 * @description: 客户端触发类
 * @author: Cheng Zhi
 * @create: 2022-10-04 15:03
 **/
public class TcpNettyClient implements NettyClient {

    /**
     * 为了后续集成agent时不产生循环打印自己的日志。
     */
    private static final Logger log = Logger.getLogger(TcpNettyClient.class.getSimpleName());

    private String hosts;

    private Integer port;

    private Bootstrap bootstrap;

    private static Channel channel;

    private HeartBeatHandler heartBeatHandler = new HeartBeatHandler(this);

    private List<Listener> messageListener = new ArrayList<>();

    private MessageHandler messageHandler;

    private IFilter<Message, Channel> filter;

    EventLoopGroup group = new NioEventLoopGroup();

    @Deprecated
    public TcpNettyClient(String hosts, Integer port) {
        this(hosts, port, null);
    }

    public TcpNettyClient(String hosts, Integer port, MessageHandler messageHandler) {
        this.messageHandler = messageHandler;
        showBanner();
        this.hosts = hosts;
        this.port = port;
        init();
    }

    /**
     * 初始化
     */
    private void init() {

        if (messageHandler == null) {
            throw new RuntimeException("请指定消息处理器！");
        }
        bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>(){

                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(ProtocalConst.PACKAGE_MAX_SIZE, 0, 8, 0, 8));
                        socketChannel.pipeline().addLast(new LengthFieldPrepender(8));
                        socketChannel.pipeline().addLast(new TcpMessageDecoder());
                        socketChannel.pipeline().addLast(new TcpMessageEncoder());
                        socketChannel.pipeline().addLast(heartBeatHandler);
                        socketChannel.pipeline().addLast(messageHandler);
                        socketChannel.pipeline().addLast(new IdleStateHandler());
                    }
                });

    }

    @Override
    public void setFilter(IFilter filter) {
        this.filter = filter;
    }

    public ChannelFuture connect() {

        synchronized (this) {
            final ChannelFuture f = bootstrap.connect(this.hosts, this.port);
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        channel = future.channel();
                    } else {
                        future.channel().pipeline().fireChannelInactive();
                    }
                }
            });
            return f;
        }
    }

    public void shutDown() {
        if (group != null) {
            group.shutdownGracefully();
        }
    }

    public boolean send(Message message) {

        if (channel == null || !channel.isActive()) {
            log.info("未连接服务器，发送失败");
            return false;
        }

        if (filter != null && filter.doFilter(message, channel)) {
            return false;
        }
        for (Listener listener : messageListener) {
            listener.before(message);
        }
        ChannelFuture f = channel.writeAndFlush(message);
        boolean success = f.isSuccess();
        for (Listener listener : messageListener) {
            listener.after(message);
        }
        return success;
    }

    public static boolean sendMsg(Message message) {
        if (channel == null || !channel.isActive()) {
            log.info("未连接服务器，发送失败");
            return false;
        }

        ChannelFuture f = channel.writeAndFlush(message);
        return f.isSuccess();
    }

    public void showBanner() {
        log.info("================================================================================");
        log.info("==     ~~~   jef TCP netty client is starting    ~~~                         ==");
        log.info("================================================================================");
    }

    @Override
    public void addListener(Listener listener) {

    }

    @Override
    public void removeListener(Listener listener) {

    }
}
